﻿
using Microsoft.AspNetCore.Mvc;
using Sykj.ViewModel;
using Sykj.IServices;
using Microsoft.AspNetCore.Authorization;
using Sykj.Components;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System;
using System.Linq;
using Sykj.Infrastructure;

namespace Sykj.Web.Api.v1
{
    /// <summary>
    /// 用户操作 bjg
    /// </summary>
    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    public class UserController : ApiController
    {
        #region 全局变量
        IUserMember _userMember;
        IGuestbook _guestbook;
        IFavorite _favorite;
        IRegions _regions;
        IPointsDetail _pointsDetail;
        IUsers _users;
        ICacheService _cacheService;
        IUserinvite _userInvite;
        #endregion

        #region 构造方法
        /// <summary>
        /// 构造方法
        /// </summary>
        public UserController(IUsers users, IUserMember userMember, IGuestbook guestbook, IFavorite favorite,IRegions regions,
            IPointsDetail pointsDetail, ICacheService cacheService, IUserinvite userInvite)
        {
            _userMember = userMember;
            _users = users;
            _favorite = favorite;
            _guestbook = guestbook;
            _regions = regions;
            _pointsDetail = pointsDetail;
            _cacheService = cacheService;
            _userInvite = userInvite;
        }
        #endregion

        #region 个人中心—用户信息 bjg
        /// <summary>
        ///  个人中心—用户信息 bjg
        /// </summary>
        /// <returns></returns>
        [HttpGet("myuserinfo")]
        public ApiResult MyUserInfo()
        {
            var model = _users.GetModel(x => x.UserId == UserId);
            if (model == null)
            {
                return Failed("用户名不存在");
            }

            var userModel = _users.GetModel(x => x.UserId == model.UserId);
            if (userModel != null)
            {
                model.Gravatar = (!string.IsNullOrWhiteSpace(userModel.Gravatar)) ? (userModel.Gravatar.StartsWith("http") ? userModel.Gravatar : BaseConfig.ImagesDoMain + userModel.Gravatar) : BaseConfig.ImagesDoMain + "/upload/user/gravatar/default.jpg";
                model.NickName = userModel.NickName;
            }
            else
            {
                model.Gravatar = BaseConfig.ImagesDoMain + "/upload/user/gravatar/default.jpg";
            }
            return DataResult(model);
        }
        #endregion

        #region 个人中心—更新用户头像 bjg
        /// <summary>
        ///  个人中心—更新用户头像 bjg
        /// </summary>
        /// <param name="fileName">头像文件路径</param>
        /// <returns></returns>
        [HttpPost("updategravatar")]
        public ApiResult UpdateGravatar(string fileName)
        {
            var model = _users.GetModel(x => x.UserId == UserId);
            if (model == null)
            {
                return Failed("用户名不存在");
            }
            model.Gravatar = fileName;
            bool b = _users.Update(model);
            if (b)
            {
                return DataResult(model);
            }
            return Failed("操作失败！请稍后重试");
        }
        #endregion

        #region  个人中心—更新用户信息 bjg
        /// <summary>
        /// 个人中心—更新用户信息 bjg
        /// </summary>
        /// <param name="userName">学生姓名</param>
        /// <param name="sex">性别</param>
        /// <param name="graduationYear">毕业年份</param>
        /// <param name="categoryType">科别类型</param>
        /// <param name="phone">手机号码</param>
        /// <param name="score">分数</param>
        /// <param name="wc">位次</param>
        /// <returns></returns>
        [HttpPost("updateuserinfo")]
        public ApiResult UpdateUserInfo(string userName, string sex, string graduationYear, string categoryType, string phone, int score = 0, int wc = 0)
        {
            var model = _users.GetModel(x => x.UserId == UserId);
            if (model == null)
            {
                return Failed("用户名不存在");
            }
            if (score > 750)
            {
                return Failed("您输入的分数过大请重新输入！");
            }
            model.Sex = sex;
            bool b = _users.Update(model);
            if (b)
            {
                return DataResult(model);
            }
            return AjaxResult(b);
        }
        #endregion

        #region 个人中心—修改密码 bjg
        /// <summary>
        /// 修改密码 bjg
        /// </summary>
        /// <param name="oldPassword">初始密码</param>
        /// <param name="newPassword">新密码</param>
        /// <param name="againPassword">再次密码</param>
        /// <returns></returns>
        [HttpPost("modifypassword")]
        public ApiResult ModifyPassword(string oldPassword, string newPassword, string againPassword)
        {
            var model = _users.GetModel(x => x.UserId == UserId);
            if (model == null)
            {
                return Failed("用户异常，请稍后再试");
            }
            if (model.Password != Infrastructure.DESEncrypt.Encrypt(oldPassword))
            {
                return Failed("原密码输入错误！请重新输入");
            }
            if (newPassword != againPassword)
            {
                return Failed("重置密码不一致，请重新输入");
            }
            model.Password = DESEncrypt.Encrypt(newPassword);
            var b = _users.Update<Entity.Users>(model, true, x => x.Password);
            return AjaxResult(b);
        }
        #endregion

        #region 添加关注 bjg
        /// <summary>
        /// 添加关注 bjg
        /// </summary>
        /// <param name="id">关注目标Id</param>
        /// <param name="type">关注类型,1商品，2商家，3文章，4,高校，5专业，6留言信息</param>
        /// <returns></returns>
        [HttpPost("addfav")]
        public ApiResult AddFav(int id, int type)
        {
            //判断用户是否已经收藏该信息
            var model = _favorite.GetModel(x => x.TargetId == id && x.Type == type && x.UserId == UserId && x.Tags == Enum.GetName(typeof(EnumHelper.Favorite), type));
            if (model != null)
            {
                //已收藏-删除
                bool bl = _favorite.Delete(model);
                if (bl)
                {
                    var cancelFav = new
                    {
                        isFavorite = false,
                        msg = "取消收藏成功"
                    };
                    return DataResult(cancelFav);
                }
                else
                {
                    return Failed("取消收藏失败,请稍后再试");
                }
            }
            else
            {
                //未收藏-添加
                Entity.Favorite addModel = new Entity.Favorite();
                addModel.TargetId = id;
                addModel.Type = type;
                addModel.Tags = Enum.GetName(typeof(EnumHelper.Favorite), type);
                addModel.CreatedDate = DateTime.Now;
                addModel.UserId = UserId;
                bool b = _favorite.Add(addModel);
                if (b)
                {
                    var addFavorite = new
                    {
                        isFavorite = true,
                        msg = "添加收藏成功"
                    };
                    return DataResult(addFavorite);
                }
                else
                {
                    return Failed("添加收藏失败,请稍后再试");
                }
            }
        }
        #endregion

        #region 个人中心—关注列表  bjg
        /// <summary>
        /// 我的关注列表  bjg
        /// </summary>
        /// <param name="pageIndex">起始页</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="type">注类型,1商品，2商家，3文章，4,高校，5专业，6留言信息</param>
        /// <returns></returns>
        [HttpGet("favoritelist")]
        public ApiResult FavoriteList(int pageIndex, int pageSize, int type)
        {
            switch (type)
            {
                case (int)EnumHelper.Favorite.Guestbook:
                    var guestBookList = _favorite.GetGuestBookPagedList(pageIndex, pageSize, "Type=@0 AND UserId=@1", "FavoriteId Desc", type, UserId).ToList();
                    guestBookList.ForEach(x =>
                    {
                        x.Gravatar = (!string.IsNullOrWhiteSpace(x.Gravatar)) ? (x.Gravatar.StartsWith("http") ? x.Gravatar : BaseConfig.ImagesDoMain + x.Gravatar) : BaseConfig.ImagesDoMain + "/upload/user/gravatar/default.jpg";
                    });
                    return DataResult(guestBookList);
                default:
                    return Failed("不存在的关注类型");
            }
        }
        #endregion

        #region 个人中心—我的留言板 bjg
        /// <summary>
        ///  个人中心—我的留言板 bjg
        /// </summary>
        /// <param name="pageIndex">起始页</param>
        /// <param name="pageSize">页大小</param>
        /// <returns></returns>
        [HttpGet("myguestbooklist")]
        public ApiResult MyGuestBookList(int pageIndex, int pageSize)
        {
            var list = _guestbook.GetPagedList(pageIndex, pageSize, "UserId=@0", "Id desc", UserId).ToList();
            list.ForEach(x =>
            {
                var userModel = _users.GetModel(c => c.UserId == x.UserId);
                if (userModel != null)
                {
                    x.Gravatar = (userModel.Gravatar != null) ? (userModel.Gravatar.StartsWith("http") ? userModel.Gravatar : BaseConfig.ImagesDoMain + userModel.Gravatar) : BaseConfig.ImagesDoMain + "/upload/user/gravatar/default.jpg";
                }
                else
                {
                    x.Gravatar = BaseConfig.ImagesDoMain + "/upload/user/gravatar/default.jpg";
                }

            });
            return DataResult(list);
        }
        #endregion

        #region 积分明细列表lh
        /// <summary>
        /// 我的积分明细列表 lh
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpPost("mypoints")]
        public ApiResult MyPoints(int pageIndex = 1, int pageSize = 10)
        {
            var model = _userMember.GetModel(c => c.UserId == UserId);
            if (model == null)
            {
                return Failed("用户信息不存在！请确认登陆");
            }
            var list = _pointsDetail.GetPagedList(pageIndex, pageSize, "UserId=@0", " CreatedDate DESC ", model.UserId);
            int count = _pointsDetail.GetRecordCount(" UserId=@0 ", model.UserId);
            return ListResult(list, count);
        }
        #endregion

    }
}